<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/home/dktjBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="打卡统计" :showBack="true"></cusHeaderVue>
		<view class="contBox" :style="{paddingTop: `calc(${scrollerHeight} + 130rpx)`}">
			<view class="contTop">
				<view class="contTit">
					打卡统计
				</view>
				<view class="contTime" @click="selectMonth">
					{{ currentMonth }}
					<u-icon name="arrow-down-fill" color="#222222" size="10"></u-icon>
				</view>
			</view>
		</view>
		<view class="contBoxBig">
			<scroll-view scroll-y="true" :refresher-enabled="true" :refresher-triggered="refreshing"
				@refresherrefresh="onRefresherRefresh"
				:style="{ height: `calc(100vh - ${scrollerHeight} - 90rpx - 195rpx)` }" @scrolltolower="onReachBottom"
				@refresherrestore="refreshing = false">
				<view class="listBox">
					<view v-if="loading && checkData.length === 0" class="loadingBox">
						<text class="loadingText">加载中...</text>
					</view>
					<view v-else-if="checkData.length === 0" class="emptyBox">
						<text class="emptyText">暂无打卡记录</text>
					</view>
					<view class="listLi" v-for="(item, index) in checkData" :key="index">
						<view class="listLeft">
							<view class="listName">
								{{ item.name || '未知门店' }}
							</view>
							<view class="listTime">
								{{ formatTime(item.createTime) }}打卡（{{ item.nickname || '未知用户' }}）
							</view>
						</view>
						<view :class="['listRight', item.type === 1 ? '' : 'listRightA']">
							{{ item.type === 1 ? '到店' : '离店' }}
						</view>
					</view>
					<view v-if="loadingMore" class="loadingMore">
						<text class="loadingMoreText">加载更多...</text>
					</view>
					<view v-if="!hasMore && checkData.length > 0" class="noMore">
						<text>已加载全部</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 月份选择器 -->

		<MonthPickerPopup ref="monthPickerRef" @confirm="onMonthConfirm" @cancel="onMonthCancel" />
	</view>
</template>

<script setup>
	import cusHeaderVue from '@/components/cus-header.vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
	import {
		GETShopCheckPage
	} from '@/api/interface.js';
	import {
		ref,
		onMounted,
		reactive,
		getCurrentInstance
	} from 'vue';
	import {
		onLoad,

	} from '@dcloudio/uni-app';

	const scrollerHeight = ref('');
	const swiperHeight = ref('');
	const monthPickerRef = ref(null);
	// 分页
	const pageNo = ref(1);
	const pageSize = ref(10);
	const hasMore = ref(true);
	const loading = ref(false);
	const loadingMore = ref(false);
	const refreshing = ref(false);

	// 响应式数据
	const checkData = ref([]);
	const showMonthPicker = ref(false);

	// 当前月份，默认显示当前月份
	const currentMonth = ref('');

	// 格式化日期（支持时间戳）
	const formatTime = (time) => {
		if (!time) return '';
		const date = new Date(time);
		const month = date.getMonth() + 1;
		const day = date.getDate();
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		const seconds = date.getSeconds().toString().padStart(2, '0');
		return `${month}/${day} ${hours}:${minutes}:${seconds}`;
	};



	// 获取打卡统计数据
	const getShopCheckData = async (isLoadMore = false) => {
		if ((isLoadMore && loadingMore.value) || (!isLoadMore && loading.value) || (!hasMore.value &&
				isLoadMore)) {
			return;
		}

		try {
			if (isLoadMore) {
				loadingMore.value = true;
			} else {
				loading.value = true;
				pageNo.value = 1;
				checkData.value = [];
				hasMore.value = true;
			}

			// 解析月份字符串为年月格式
			const monthStr = currentMonth.value;
			let queryMonth = '';
			if (monthStr) {
				const match = monthStr.match(/(\d+)年(\d+)月/);
				if (match) {
					queryMonth = `${match[1]}-${parseInt(match[2]).toString().padStart(2, '0')}`;
				}
			}
			const userInfo = uni.getStorageSync('userInfo') || {};
			const params = {
				pageNo: pageNo.value,
				pageSize: pageSize.value,
				monthStr: queryMonth,
				uid: userInfo.userType == 0 ? userInfo.id : ""
			};

			const res = await GETShopCheckPage(params);

			if (res.code === 0 && res.data) {
				// 根据新的数据格式，使用res.data.list作为记录列表
				const records = res.data.list || [];
				if (isLoadMore) {
					checkData.value = [...checkData.value, ...records];
				} else {
					checkData.value = records;
				}

				// 判断是否还有更多数据
				hasMore.value = checkData.value.length < res.data.total;
				if (hasMore.value) {
					pageNo.value++;
				}
			} else {
				uni.showToast({
					title: res.message || '获取数据失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			});
			console.error('获取打卡统计数据失败:', error);
		} finally {
			loading.value = false;
			loadingMore.value = false;
			refreshing.value = false;
		}
	};

	// 下拉刷新
	const onRefresherRefresh = () => {
		refreshing.value = true;
		getShopCheckData(false);
	};

	// 加载更多
	const onReachBottom = () => {
		if (hasMore.value && !loadingMore.value) {
			getShopCheckData(true);
		}
	};
	// 打开年月选择器
	const selectMonth = () => {
		monthPickerRef.value.open();
	};


	// 处理月份选择确认
	const onMonthConfirm = (month) => {
		currentMonth.value = month;
		getShopCheckData(false);
	};

	// 初始化当前月份
	const initCurrentMonth = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth() + 1;
		currentMonth.value = `${year}年${month}月`;
	};


	onLoad(() => {
		const userInfo = uni.getStorageSync('userInfo') || {};
		console.log(userInfo)
		console.log(userInfo)
		console.log(userInfo)
		initCurrentMonth();
		getBarHeight();

	})

	onMounted(() => {
		getShopCheckData(false);
	})

	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(resu) {
				scrollerHeight.value = resu.statusBarHeight + 'px'
				// resu 可以获取当前屏幕的高度
				const query = uni.createSelectorQuery();
				query.select('.contBoxBig').boundingClientRect(); //.swiper是swiper类名，获取当前swiper距离顶部的位置
				query.exec(res => {
					swiperHeight.value = resu.windowHeight - res[0].top - resu.safeAreaInsets
						.bottom - resu.statusBarHeight - 70 +
						'px'; //屏幕的高度减去当前swiper距离顶部的高度就是剩余屏幕的高度 然后动态赋值给swiper
				});
			}
		});
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 750rpx;
		height: 740rpx;
		position: absolute;
		z-index: -1;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		width: 100%;
		padding: 22rpx;
		box-sizing: border-box;

		.contTop {
			padding: 0 24rpx;
			box-sizing: border-box;

			.contTit {
				font-weight: 500;
				font-size: 44.87rpx;
				color: #926B12;
			}

			.contTime {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				width: 210.9rpx;
				height: 56.41rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #ffffff;
				margin-top: 24rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				color: #222222;
				font-weight: 400;
				font-size: 29.49rpx;
				padding: 0 22rpx;
				box-sizing: border-box;

				// 添加点击效果
				&:active {
					background-color: #f5f5f5;
				}
			}
		}
	}

	.contBoxBig {
		padding: 10rpx 22rpx;
		box-sizing: border-box;

		.listBox {

			// 加载中样式
			.loadingBox {
				width: 100%;
				height: 200rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.loadingText {
					margin-top: 20rpx;
					font-size: 28rpx;
					color: #926B12;
				}
			}

			// 空状态样式
			.emptyBox {
				width: 100%;
				height: 200rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.emptyText {
					font-size: 28rpx;
					color: #999999;
				}
			}

			// 列表项样式
			.listLi {
				width: 100%;
				border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
				background: #ffffff;
				padding: 35rpx 27rpx;
				box-sizing: border-box;
				margin-bottom: 19rpx;
				display: flex;
				align-items: center;

				.listLeft {
					flex: 1;

					.listName {
						font-weight: 500;
						font-size: 33.33rpx;
						color: #1C2027;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 505rpx;
					}

					.listTime {
						color: #7f8494;
						font-weight: 400;
						font-size: 25.64rpx;
						margin-top: 22rpx;
					}
				}

				.listRight {
					width: 89.74rpx;
					height: 46.15rpx;
					border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
					background: #ffffff;
					font-size: 25.64rpx;
					font-weight: 400;
					color: #02A360;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 1px solid #02A360;
				}

				.listRightA {
					color: #FA871E;
					border: 1px solid #FA871E;
				}
			}

			// 加载更多样式
			.loadingMore {
				width: 100%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.loadingMoreText {
					margin-left: 10rpx;
					font-size: 24rpx;
					color: #926B12;
				}
			}

			// 没有更多数据样式
			.noMore {
				width: 100%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					font-size: 24rpx;
					color: #999999;
				}
			}
		}
	}
</style>